package src.week4.PP617;

import src.week4.LinearNode;
import src.week4.LinkedList;
import src.week4.OrderedListADT;

import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;

public  class LinkedOrderedList implements Iterable<Course2>
{
    protected int count;
    protected LinearNode<Course2> head, tail;
    protected int modCount;

    public LinkedOrderedList() {
        count = 0;
        head = tail = null;
        modCount = 0;
    }
    public void addCourse(Course2 course) {

        LinearNode<Course2> temp = new LinearNode(course);

        LinearNode<Course2> previous = null;

        LinearNode<Course2> current = head;

        while(current != null && course.campareTo(current.getElement())> 0){
            previous = current;
            current = current.getNext();
        }
        if(previous == null){
            head = tail =  temp;
        }
        else{
            previous.setNext(temp);
        }
        temp.setNext(current);
        if(temp.getNext() == null)
            tail = temp;
        count++;
        modCount++;
    }
    @Override
    public String toString()
    {
        int n = count;
        String result = "";
        LinearNode<Course2> current = head;
        while(n > 0){
            result += current.getElement()+"\n";
            current = current.getNext();
            n--;
        }
        return result;
    }

    @Override
    public Iterator<Course2> iterator() {
        return new LinkedListIterator();
    }
    private class LinkedListIterator implements Iterator<Course2> {
        private int iteratorModCount;
        private LinearNode<Course2> current;
        public LinkedListIterator() {
            current = head;
            iteratorModCount = modCount;
        }
        @Override
        public boolean hasNext() throws ConcurrentModificationException {
            if (iteratorModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            return (current != null);
        }
        @Override
        public Course2 next() throws ConcurrentModificationException {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            Course2 result = current.getElement();
            current = current.getNext();
            return result;
        }
        @Override
        public void remove() throws UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }
    }
}


